﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.Apis.Tasks.v1.Data;

namespace G_Tasks
{
    public class NoteItem
    {
        public string NoteText;
        public bool NoteFinished;
        public DateTime NoteDue;

        public bool Modified;
        public Task RelatedTask;

        public NoteItem(Task task)
        {
            Modified = false;
            RelatedTask = task;
            NoteText = task.Title;
            // pokud je ukol na více řádků další řádky se berou jako poznámka, první jako titulek
            if (!String.IsNullOrEmpty(task.Notes))
                NoteText += Environment.NewLine + task.Notes.Replace("\n", Environment.NewLine);
            NoteFinished = !String.IsNullOrEmpty(task.Completed);
            NoteDue = String.IsNullOrEmpty(task.Due) ? DateTime.MaxValue : DateTime.Parse(task.Due);
        }

        public void SubmitChanges()
        {
            if (NoteText.Contains(Environment.NewLine))
            {
                RelatedTask.Title = NoteText.Substring(0, NoteText.IndexOf(Environment.NewLine));
                RelatedTask.Notes = NoteText.Substring(NoteText.IndexOf(Environment.NewLine) + Environment.NewLine.Length).Replace(Environment.NewLine, "\n");
            }
            else
                RelatedTask.Title = NoteText;

            RelatedTask.Status = NoteFinished ? "completed" : "needsAction";

            if ((NoteFinished) && (String.IsNullOrEmpty(RelatedTask.Completed)))
                RelatedTask.Completed = DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ssZ");
            else
                RelatedTask.Completed = null;

            if (NoteDue != DateTime.MaxValue)
                RelatedTask.Due = NoteDue.ToString("yyyy-MM-dd'T'HH:mm:ssZ");
            else
                RelatedTask.Due = null;

            Modified = true;
        }

        /// <summary>
        /// Vrátí datum nastavené u úkolu - není li vrátí: None. Pokud je to dnes: Today, jinak datum ve tvaru 12.2.2013
        /// </summary>
        /// <returns></returns>
        public string DueToDateString()
        {
            if (NoteDue == DateTime.MaxValue)
                return "None";
            if (NoteDue.Date == DateTime.Today.Date)
                return "Today";
            return NoteDue.ToShortDateString();
        }
    }
}
